package com.example.demo.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;

import java.security.MessageDigest;
import java.util.*;

/**
 * @Classname Md5SignUtil
 * @Description TODO
 * @Date 2019/9/3 14:03
 * @Created by yby
 */
public class Md5SignUtil {

    /**
     * 使用md5算法进行加密
     *
     * @param target  要加密的字符串
     * @param charset 编码（请设置为UTF-8)
     * @return 加密后的字符串
     */
    public static String encryptWithMD5(String target, String charset) {
        String md5Str = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.reset();
            byte[] bytes = md5.digest(charset == null ? target.getBytes() : target.getBytes(charset));
            StringBuffer stringBuffer = new StringBuffer();
            for (byte b : bytes) {
                int bt = b & 0xff;
                if (bt < 16) {
                    stringBuffer.append(0);
                }
                stringBuffer.append(Integer.toHexString(bt));
            }
            md5Str = stringBuffer.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return md5Str;
    }

    public static String getSign(Map<String, String> params, String key) {

        /**
         * 对params中的参数进行排序后生成签名串
         * @param params 参与签名的参数map
         * @param key 签名要用到的加密串
         * @return
         */
        String sign = null;
        StringBuffer sb = new StringBuffer();
        //排序
        List<Map.Entry<String, String>> infoIds =
                new ArrayList<Map.Entry<String, String>>(params.entrySet());
        Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                return (o1.getKey()).toString().compareTo(o2.getKey());
            }
        });
        //对参数数组进行按key升序排列,然后拼接，最后调用5签名方法
        int size = infoIds.size();
        for (int i = 0; i < size; i++) {
            if (!StringUtils.isEmpty(infoIds.get(i).getValue())) {//不为空，为空的不参与签名
                sb.append(infoIds.get(i).getKey() + "=" + infoIds.get(i).getValue() + "&");
            }
        }
        String newStrTemp = sb.toString() + "key=" + key.trim();
        //获取sign_method

        sign = encryptWithMD5(newStrTemp, "UTF-8");

        return sign;
    }

    public static void main(String[] args) {
        //返回集合
        JSONArray jsonArray = new JSONArray();
        //福彩数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("buyType", "1");  //1为福彩
        jsonObject.put("buyNumber", 22);  //购买数量
        //jsonObject.put("welfareType","10元"); //福彩类型
        jsonObject.put("welfareSize", 11); //福彩尺寸

        //jsonArray.put(jsonObject);
        jsonArray.add(jsonObject);

        //体彩数据
        jsonObject = new JSONObject();
        jsonObject.put("buyType", "2");//2为体彩
        jsonObject.put("buyNumber", 33);//购买数量
        //jsonObject.put("sportsType","5元"); //体彩类型
        jsonObject.put("sportsSize", 11); //体彩尺寸
        //jsonArray.put(jsonObject);
        jsonArray.add(jsonObject);

        //参数签名算法测试例子
        HashMap<String, String> signMap = new HashMap<String, String>();
        signMap.put("cpOdd", "12AAFF");
        signMap.put("orderId", "15683");
        signMap.put("param", jsonArray.toJSONString());
        //signMap.put("time",String.valueOf(System.currentTimeMillis()));
        signMap.put("time", "1567477313594");
        String secret_key = "02f7e697217940d08a48aa0be96962ee"; //加密secret
        String sign = getSign(signMap, secret_key);
        //System.out.println("SignHashMap:"+SignHashMap);
        //System.out.println("参数:"+jsonArray.toJSONString());
        //获取参数签名字符串
        System.out.println("得到签名sign2:" + sign);
    }
}
